# -*- coding:utf-8 -*-
"""
客户端入口
开启四个子线程进行相关监控
1，键盘监控线程  monitor_keyboard
2，通信服务线程 monitor_message
3，界面线程
4，在主线程实现界面实例与通信实例信息交换
"""
import Keyboard
import Message
import threading
import View
import time
import GlobalVar


class Client:
    def __init__(self):
        fh = open('./server.conf', 'r')
        server_ip = fh.readline()
        fh.close()
        self.message = Message.MessageClient(server_ip, 8080)
        self.monitor_message()
        self.keyboard = Keyboard.Keyboard(self.message)
        self.monitor_keyboard()
        self.view = View.View()
        self.master()

    def monitor_message(self):
        """
        开启一个消息监控线程
        :return: void
        """

        def thread_message(message_obj):
            message_obj.monitor()

        my_thread = threading.Thread(target=thread_message, args=(self.message,))
        my_thread.start()

    def monitor_keyboard(self):
        """
        开启一个键盘监控线程
        :return: void
        """

        def thread_keyboard(keyboard_obj):
            keyboard_obj.monitor()

        my_thread = threading.Thread(target=thread_keyboard, args=(self.keyboard,))
        my_thread.start()

    def master(self):
        """
        界面实例与通信实例信息交换
        :return: void
        """

        def thread_monitor():
            while True:
                time.sleep(0.001)
                if GlobalVar.get_list():
                    self.view.reset_list_box(GlobalVar.get_list())
                    GlobalVar.set_list(False)

                if GlobalVar.get_switch():
                    self.message.send_control(GlobalVar.get_switch())
                    GlobalVar.set_switch(False)

        my_thread = threading.Thread(target=thread_monitor)
        my_thread.start()


if __name__ == '__main__':
    clientObj = Client()
    clientObj.view.run()
